﻿Imports System.Windows.Forms
Imports CodeDefinition
Imports System.Windows.Interop
Imports System.CodeDom
Imports System.IO

Class Mainform

    Private _ApplicationObjectInstance As ApplicationObject
    Private Property ApplicationObjectInstance() As ApplicationObject
        Get
            Return _ApplicationObjectInstance
        End Get
        Set(ByVal value As ApplicationObject)
            _ApplicationObjectInstance = value
        End Set
    End Property

    Private _ClassObjectInstance As ClassObject
    Public Property ClassObjectInstace() As ClassObject
        Get
            Return _ClassObjectInstance
        End Get
        Set(ByVal value As ClassObject)
            _ClassObjectInstance = value
        End Set
    End Property

    Private _XMLFilePath As String
    Private Property XMLFilePath() As String
        Get
            Return _XMLFilePath
        End Get
        Set(ByVal value As String)
            _XMLFilePath = value
            txtPathToXMLFile.Text = value
            txtApplicationRootPath.Text = New DirectoryInfo(value).Parent.FullName
        End Set
    End Property

    Private Sub SaveSettings()
        Dim myApplicationObject As ApplicationObject = ApplicationObjectInstance

        'fill the object with values
        With myApplicationObject
            'Application
            .Name = txtApplicationName.Text
            .ApplicationDirectory = txtApplicationRootPath.Text
            .BlankLinesBetweenMembers = chkBoxBlankLinesBetweenMembers.IsChecked
            .VerbatimOrder = chkboxVerbatimOrder.IsChecked

            Select Case CType(cboGeneratorType.SelectedValue, ComboBoxItem).Name
                Case cboGeneratorTypeCSharp.Name
                    .GeneratorType = ApplicationObject.enmGeneratorType.CSharp
                Case cboGeneratorTypeVB.Name
                    .GeneratorType = ApplicationObject.enmGeneratorType.VisualBasic
                Case cboGeneratorTypeVisualBasicAndCSharp.Name
                    .GeneratorType = ApplicationObject.enmGeneratorType.VisualBasicAndCSharp
            End Select

            UpdateClassObject()

        End With

        'save it to the local instance
        ApplicationObjectInstance = myApplicationObject

        'save it
        Dim myXMLFilePath As String = XMLFilePath
        myApplicationObject.SaveApplicationObject(myXMLFilePath)
    End Sub

    Private Sub btnSelectApplicationRootPath_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSelectApplicationRootPath.Click
        'select path

        Dim myDlg As System.Windows.Forms.FolderBrowserDialog = New FolderBrowserDialog()
        Dim source As HwndSource = TryCast(PresentationSource.FromVisual(Me), HwndSource)
        Dim win As System.Windows.Forms.IWin32Window = New SelectFolder(source.Handle)

        With myDlg
            .Description = "Select the output path. It's the base path from where the generator will start to create the files"
            .ShowNewFolderButton = False
            .SelectedPath = txtApplicationRootPath.Text
        End With

        Dim result As System.Windows.Forms.DialogResult = myDlg.ShowDialog(win)
        If result = Forms.DialogResult.OK Then
            txtApplicationRootPath.Text = myDlg.SelectedPath
        End If
    End Sub

    Private Sub btnSelectXMLFile_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSelectXMLFile.Click
        SelectXMLFile(bCheckIfFileExist:=True)
        ReadXML()
    End Sub

    Private Sub ReadXML()
        Dim myPathToXMLFile As String = txtPathToXMLFile.Text

        'check if the file exit
        If Not System.IO.File.Exists(myPathToXMLFile) Then Throw New ArgumentException(String.Format("The configuration file '{0}' could not be found", myPathToXMLFile))

        'create the appliationobject
        Dim myApplicationObject As ApplicationObject = CodeDefinition.ApplicationObject.CreateApplicationObjectFromXML(myPathToXMLFile)
        ApplicationObjectInstance = myApplicationObject

        'update the screen

        'application
        txtApplicationName.Text = myApplicationObject.Name
        If (Not myApplicationObject.ApplicationDirectory Is Nothing) AndAlso (myApplicationObject.ApplicationDirectory.Trim.Length > 0) Then
            txtApplicationRootPath.Text = myApplicationObject.ApplicationDirectory
        End If

        chkboxVerbatimOrder.IsChecked = myApplicationObject.VerbatimOrder
        chkBoxBlankLinesBetweenMembers.IsChecked = myApplicationObject.BlankLinesBetweenMembers
        Dim myGeneratorType As ApplicationObject.enmGeneratorType = myApplicationObject.GeneratorType
        Select Case myGeneratorType
            Case ApplicationObject.enmGeneratorType.CSharp
                cboGeneratorType.SelectedItem = cboGeneratorTypeCSharp
            Case ApplicationObject.enmGeneratorType.VisualBasic
                cboGeneratorType.SelectedItem = cboGeneratorTypeVB
            Case ApplicationObject.enmGeneratorType.VisualBasicAndCSharp
                cboGeneratorType.SelectedItem = cboGeneratorTypeVisualBasicAndCSharp
            Case Else
                'not set
                cboGeneratorType.SelectedIndex = -1
        End Select

        'classnames
        lstBoxClasses.Items.Clear()

        For Each myClassObject As ClassObject In myApplicationObject.ClassObjects
            lstBoxClasses.Items.Add(myClassObject.Name)
        Next


        gridApplicationSettings.Visibility = Windows.Visibility.Visible

        btnRunGenerator.Visibility = Windows.Visibility.Visible

    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        SaveSettings()
    End Sub

    Private _GeneratorFeedback As CodeGenerator.GeneratorFeedback
    Public Property GeneratorFeedback() As CodeGenerator.GeneratorFeedback
        Get
            Dim myGeneratorFeedback As CodeGenerator.GeneratorFeedback = _GeneratorFeedback
            If myGeneratorFeedback Is Nothing Then
                myGeneratorFeedback = New CodeGenerator.GeneratorFeedback
                _GeneratorFeedback = myGeneratorFeedback
            End If
            Return myGeneratorFeedback
        End Get
        Set(ByVal value As CodeGenerator.GeneratorFeedback)
            _GeneratorFeedback = value
        End Set
    End Property

    Private Sub btnRunGenerator_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRunGenerator.Click

        Me.Cursor = System.Windows.Input.Cursors.Wait


        'save config
        SaveSettings()

        'read out what file we will create
        Dim myGenerate_DO As Boolean = True 'chkBoxGenerate_DO.IsChecked

        'clear the feedback textbox
        'txtGeneratorFeedback.Text = String.Empty

        'start to create
        Try
            GeneratorFeedback = CodeGenerator.ExternalInterface.Run(aFileNameToXMLFile:=XMLFilePath, aDO:=myGenerate_DO)

            'finish without error
            Me.Cursor = System.Windows.Input.Cursors.Arrow

            'show the result
            RefreshGeneratorFeedback()

        Catch ex As Exception
            Me.Cursor = System.Windows.Input.Cursors.Arrow
            MsgBox(ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly)
        Finally
            Me.Cursor = System.Windows.Input.Cursors.Arrow
        End Try

    End Sub

    Private Sub lstBoxClasses_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
        Dim myClassName As String = Nothing
        For Each myName As String In e.AddedItems
            myClassName = myName
            Exit For
        Next
        If myClassName Is Nothing OrElse myClassName.Trim.Length = 0 Then Return
        ShowClassDefinintion(ApplicationObjectInstance.GetClassObjectByName(myClassName))
    End Sub

    'Private Sub cboClassDefinitions_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
    '    Dim myClassObject As ClassObject = Nothing
    '    For Each myClassObj As ClassObject In e.AddedItems
    '        myClassObject = myClassObj
    '        Exit For
    '    Next
    '    ShowClassDefinintion(myClassObject)
    'End Sub

    Private Sub UpdateClassObject()
        If ClassObjectInstace Is Nothing Then Return
        With ClassObjectInstace
            'save the old values
            .ClassNamespaceName = txtNamespace.Text
            .Name = txtName.Text

            'add the namespaces
            Dim myNamespacesToImport As New List(Of String)
            For Each myItem As String In lstNamespacesToImport.Items
                .NamespacesToImport.Add(myItem)
            Next

            With .MemberAttributeObject
                .[Public] = cboPublic.IsChecked
                .[Abstract] = cboAbstract.IsChecked
                .[StaticShared] = cboStaticShared.IsChecked
            End With
        End With
    End Sub

    Private Sub ShowClassDefinintion(ByVal aObjectClass As ClassObject)

        ' save the old values
        UpdateClassObject()

        'save the ClassObjectInterface
        ClassObjectInstace = aObjectClass

        ' Class definition
        Dim myName As String = aObjectClass.Name.ToLowerInvariant

        With aObjectClass
            txtNamespace.Text = .ClassNamespaceName
            txtName.Text = .Name

            lstNamespacesToImport.Items.Clear()
            For Each myItem As String In .NamespacesToImport
                If Not lstNamespacesToImport.Items.Contains(myItem) Then lstNamespacesToImport.Items.Add(myItem)
            Next

            With .MemberAttributeObject
                cboPublic.IsChecked = .[Public]
                cboStaticShared.IsChecked = .[StaticShared]
                cboAbstract.IsChecked = .[Abstract]
            End With
        End With

    End Sub

    Private Sub SelectXMLFile(ByVal bCheckIfFileExist As Boolean)
        Dim myFileSelectDialog As New Microsoft.Win32.OpenFileDialog
        With myFileSelectDialog
            .CheckFileExists = bCheckIfFileExist
            .CheckPathExists = True
            .DefaultExt = ".xml"
            .Filter = "*.xml|*.xml|*.*|*.*"
            .FilterIndex = 0
            .Multiselect = False
            .RestoreDirectory = True
            If .ShowDialog Then
                XMLFilePath = .FileName
            End If
        End With
    End Sub

    Private Sub Window1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        btnRunGenerator.Visibility = Windows.Visibility.Hidden
        gridApplicationSettings.Visibility = Windows.Visibility.Hidden
    End Sub

    Private Sub btnCreateDemoXMLFile_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        'ask for the path
        SelectXMLFile(bCheckIfFileExist:=False)

        Dim myXMLPathFile As String = XMLFilePath

        If (XMLFilePath Is Nothing) OrElse (XMLFilePath.Trim.Length = 0) Then
            MsgBox("You must first select a filename")
            Return
        End If

        'create a file
        Dim myApplictionPath As String = New DirectoryInfo(myXMLPathFile).Parent.FullName
        CodeDefinition.DemoData.CreateDemoXML(myXMLPathFile, True, myApplictionPath)

        'now we read out the files
        ReadXML()

    End Sub

    Private Sub lstBoxProperties_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
        'todo Properties
    End Sub

    Private Sub btnRefreshGeneratorFeedback_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        RefreshGeneratorFeedback()
    End Sub

    Private Sub RefreshGeneratorFeedback()
        'show the answer
        'txtGeneratorFeedback.Text = GeneratorFeedback.ToString(chkBoxShowDetails.IsChecked)
        'TabControl1.SelectedItem = TabItemGeneratorFeedback
    End Sub

    Private Sub chkBoxShowDetails_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        RefreshGeneratorFeedback()
    End Sub

    Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        SelectXMLFile(True)
    End Sub
End Class
